﻿using log4net;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Transactions;
using System.Web;
using System.Web.Services;
using Thrift.Route;

namespace WebServiceSmart
{
    public partial class MyService
    {

        //查询订单状态
        [WebMethod(Description = "查询订单状态")]
        public void XYF_GetOrderStatus()
        {
            ILog logJieKou = LogManager.GetLogger("LoggerZhiFu");
            string result = @"{ 
                     'code':'0',  
                     'msg':'请求成功'
                 }";
            JObject ret = JObject.Parse(result);


            Stream postData = Context.Request.InputStream;
            StreamReader sRead = new StreamReader(postData);
            string postContent = sRead.ReadToEnd();
            logJieKou.Info(nameof(XYF_GetOrderStatus) + "-" + postContent);
            mysqlcli mainsql = new mysqlcli();
            mainsql.openShopServicesql();
            try
            {
                var orderid = Context.Request.Form["order_no"];
                var data = new JObject();
                data.Add("order_no", orderid);
                var model = mainsql.SqlExcuteWithReturn($"select * from {S_ORDER} where order_number='{orderid}'").ToModels().FirstOrDefault();
                if (model != null && model.Keys.Count > 0)
                {
                    //1-待支付、2-已关闭、3-支付中、4-已支付、5-待退款、6-已退款
                    var order_status = model["order_status"].ToInt32();
                    var order_pay_status = model["order_pay_status"].ToInt32();
                    if (order_status == 0)
                    {
                        //新订单
                        if (order_pay_status == 1)
                        {
                            //支付中
                            data.Add("status", 3);
                        }
                        else if (order_pay_status == 0)
                        {
                            //未付款
                            data.Add("status", 1);
                        }
                    }
                    else if (order_status == 1 || order_status == 2)
                    {
                        //已支付,待发货
                        data.Add("status", 4);
                    }
                    else if (order_status == 3)
                    {
                        //已完成订单
                        data.Add("status", 2);
                    }
                    else if (order_status == 4)
                    {
                        //申请取消
                        data.Add("status", 5);
                    }
                    else if (order_status == 5)
                    {
                        //已取消
                        data.Add("status", 6);
                    }
                }
                else
                {
                    ret["msg"] = "不存在的订单号";
                    ret["code"] = "1";
                    goto EXIT;
                }
                ret.Add("data", data);

            }
            catch (Exception ex)
            {
                ret["msg"] = ex.Message;
                ret["code"] = "1";
                logJieKou.Info(ex);
            }

            EXIT:
            mainsql.closesql();
            logJieKou.Info("订单状态回调结束：" + ret.ToString());
            Context.Response.Charset = "UTF-8";
            Context.Response.ContentEncoding = System.Text.Encoding.GetEncoding("UTF-8");
            Context.Response.Write(ret.ToString());
            Context.Response.End();
        }

        //查询订单详情
        [WebMethod(Description = "查询订单详情")]
        public void XYF_GetOrderInfo()
        {
            ILog logJieKou = LogManager.GetLogger("LoggerZhiFu");
            string result = @"{ 
                     'code':'0',  
                     'msg':'请求成功'
                 }";
            JObject ret = JObject.Parse(result);


            Stream postData = Context.Request.InputStream;
            StreamReader sRead = new StreamReader(postData);
            string postContent = sRead.ReadToEnd();
            logJieKou.Info(nameof(XYF_GetOrderInfo) + "-" + postContent);
            mysqlcli mainsql = new mysqlcli();
            mainsql.openShopServicesql();
            try
            {
                var orderid = Context.Request.Form["order_no"];
                var model = mainsql.SqlExcuteWithReturn($"select t1.*,t2.user_phone,t2.user_name,t3.shop_name,t3.shop_tel_number,t3.shop_address from {S_ORDER} t1 left join {BIAOUSER} t2 on t1.order_to_user_id=t2.user_onlyid left join {BIAOSHOP} t3 on t1.shop_id=t3.shop_id where order_number='{orderid}'").ToModels().FirstOrDefault();
                if (model == null || model.Keys.Count == 0)
                {
                    ret["msg"] = "不存在的订单号";
                    ret["code"] = "1";
                    goto EXIT;
                }
                var data = new JObject();
                data.Add("order_no", orderid);//订单号
                var order_status = model["order_status"].ToInt32();
                var order_pay_status = model["order_pay_status"].ToInt32();
                //运单状态
                //1-待揽收2 - 已揽收3 - 已发车4 - 待提货5 - 已签收6 - 退货

                if (order_status == 0)
                {
                    data.Add("transport_status", 1);
                    //新订单
                    if (order_pay_status == 1)
                    {
                        //支付中
                        data.Add("status", 3);
                    }
                    else if (order_pay_status == 0)
                    {
                        //未付款
                        data.Add("status", 1);
                    }
                }
                else if (order_status == 1 || order_status == 2)
                {
                    data.Add("transport_status", 2);
                    //已支付,待发货
                    data.Add("status", 4);
                }
                else if (order_status == 3)
                {
                    data.Add("transport_status", 5);
                    //已完成订单
                    data.Add("status", 2);
                }
                else if (order_status == 4)
                {
                    //申请取消
                    data.Add("status", 5);
                    data.Add("transport_status", 6);
                }
                else if (order_status == 5)
                {
                    //已取消
                    data.Add("status", 6);
                    data.Add("transport_status", 6);
                }
                var payTime = model["order_pay_time"].ToDateTime();
                if (payTime.HasValue)
                {
                    data.Add("pay_time", payTime.Value.ToString("yyyy-MM-dd HH:mm:ss")); //支付时间
                    data.Add("is_payed", 1); //支付状态
                }
                else
                {
                    data.Add("pay_time", ""); //支付时间
                    data.Add("is_payed", 0); //支付状态
                }
                data.Add("pay_type", 3); //支付方式
                data.Add("create_time", model["order_create_time"].ToDateTime().Value.ToString("yyyy-MM-dd HH:mm:ss")); //建单时间
                data.Add("amount", model["order_price"].ToDouble() * 100);//分 订单金额
                data.Add("pay_money", model["order_price"].ToDouble() * 100);//分  实际支付金额
                data.Add("discount_amount", 0 * 100);//分 优惠金额

                data.Add("seller_staff_id", string.Empty);//卖家编号
                data.Add("seller_mobile_no", model["shop_tel_number"]); //卖家电话
                data.Add("seller_name", model["shop_name"]);  //卖家名称

                data.Add("buyer_staff_id", string.Empty); //买家编号
                data.Add("buyer_name", model["user_name"]);  //买家名称
                data.Add("buyer_mobile_no", model["user_phone"]);  //买家电话

                System.Text.StringBuilder products = new System.Text.StringBuilder();
                var prds = mainsql.SqlExcuteWithReturn($"select * from {BIAOORDERPRODUCT} where order_id='{model["order_id"]}'").ToModels();
                var productnum = 0;
                foreach (var item in prds)
                {
                    productnum++;
                    products.AppendFormat("{0}*{1}", item["order_prd_name"], item["order_prd_number"]);
                }

                data.Add("goods_name", products.ToString());//产品
                data.Add("goods_num", productnum); //产品数量

                data.Add("transport_no", model["order_ems_number"]); //运单号
                var deliverTime = model["order_to_time"].ToDateTime();
                if (deliverTime.HasValue)
                    data.Add("deliver_time", deliverTime.Value.ToString("yyyy-MM-dd HH:mm:ss")); //发货时间
                else data.Add("deliver_time", ""); //发货时间
                var receiveTime = model["order_from_time"].ToDateTime();
                if (receiveTime.HasValue)
                    data.Add("receive_time", receiveTime.Value.ToString("yyyy-MM-dd HH:mm:ss")); //收货时间
                else data.Add("receive_time", "");

                data.Add("receiver_name", model["order_to_user"]);  //收货人
                data.Add("receiver_tel", model["order_to_phone"]);  //收货电话
                data.Add("receiver_address", model["order_to_address"]);  //收货地址
                data.Add("receiver_province_name", string.Empty);  //收货省份
                data.Add("receiver_city_name", string.Empty);  //收货城市
                data.Add("receiver_region_name", string.Empty);  //收货地区
                data.Add("sender_tel", model["shop_tel_number"]); //卖家电话
                data.Add("sender_name", model["shop_name"]);  //卖家名称
                data.Add("sender_address", model["shop_address"]);  //发货地址
                data.Add("Sender_province_name", string.Empty);  //发货省份
                data.Add("sende _city_name", string.Empty);  //发货城市
                data.Add("sender_region_name", string.Empty);  //发货地区
                data.Add("logistics_company_name", model["order_ems_name"]);  //物流公司

                ret.Add("data", data);
            }
            catch (Exception ex)
            {
                ret["msg"] = ex.Message;
                ret["code"] = "1";
                logJieKou.Info(ex);
            }

            EXIT:
            mainsql.closesql();
            logJieKou.Info("订单详情回调结束：" + ret.ToString());
            Context.Response.Charset = "UTF-8";
            Context.Response.ContentEncoding = System.Text.Encoding.GetEncoding("UTF-8");
            Context.Response.Write(ret.ToString());
            Context.Response.End();
        }

        //查询运单详情
        [WebMethod(Description = "查询运单详情")]
        public void XYF_GetWayInfo()
        {
            ILog logJieKou = LogManager.GetLogger("LoggerZhiFu");
            string result = @"{ 
                     'code':'0',  
                     'msg':'请求成功'
                 }";
            JObject ret = JObject.Parse(result);


            Stream postData = Context.Request.InputStream;
            StreamReader sRead = new StreamReader(postData);
            string postContent = sRead.ReadToEnd();
            logJieKou.Info(nameof(XYF_GetOrderInfo) + "-" + postContent);

            mysqlcli mainsql = new mysqlcli();
            mainsql.openShopServicesql();
            try
            {
                var orderid = Context.Request.Form["order_no"];
                var model = mainsql.SqlExcuteWithReturn($"select t1.*,t2.user_phone,t2.user_name,t3.shop_name,t3.shop_tel_number,t3.shop_address from {S_ORDER} t1 left join {BIAOUSER} t2 on t1.order_to_user_id=t2.user_onlyid left join {BIAOSHOP} t3 on t1.shop_id=t3.shop_id where order_number='{orderid}'").ToModels().FirstOrDefault();
                if (model == null || model.Keys.Count == 0)
                {
                    ret["msg"] = "不存在的订单号";
                    ret["code"] = "1";
                    goto EXIT;
                }
                var data = new JObject();
                data.Add("order_no", orderid);//订单号
                data.Add("transport_no", model["order_ems_number"]); //运单号
                var order_status = model["order_status"].ToInt32();
                var order_pay_status = model["order_pay_status"].ToInt32();
                //运单状态
                //1-待揽收2 - 已揽收3 - 已发车4 - 待提货5 - 已签收6 - 退货

                if (order_status == 0)
                {
                    data.Add("transport_status", 1);
                }
                else if (order_status == 1)
                {
                    data.Add("transport_status", 2);
                }
                else if (order_status == 2)
                {
                    data.Add("transport_status", 2);
                }
                else if (order_status == 3)
                {
                    data.Add("transport_status", 5);
                }
                else if (order_status == 4)
                {
                    data.Add("transport_status", 6);
                }
                else if (order_status == 5)
                {
                    data.Add("transport_status", 6);
                }

                var deliverTime = model["order_to_time"].ToDateTime();
                if (deliverTime.HasValue)
                    data.Add("deliver_time", deliverTime.Value.ToString("yyyy-MM-dd HH:mm:ss")); //发货时间
                else data.Add("deliver_time", ""); //发货时间
                var receiveTime = model["order_from_time"].ToDateTime();
                if (receiveTime.HasValue)
                    data.Add("receive_time", receiveTime.Value.ToString("yyyy-MM-dd HH:mm:ss")); //收货时间
                else data.Add("receive_time", "");

                data.Add("receiver_name", model["order_to_user"]);  //收货人
                data.Add("receiver_tel", model["order_to_phone"]);  //收货电话
                data.Add("receiver_address", model["order_to_address"]);  //收货地址

                data.Add("sender_tel", model["shop_tel_number"]); //卖家电话
                data.Add("sender_name", model["shop_name"]);  //卖家名称
                data.Add("sender_address", model["shop_address"]);  //发货地址
                data.Add("logistics_company_name", model["order_ems_name"]);  //物流公司

                ret.Add("data", data);
            }
            catch (Exception ex)
            {
                ret["msg"] = ex.Message;
                ret["code"] = "1";
                logJieKou.Info(ex);
            }

            EXIT:
            mainsql.closesql();
            logJieKou.Info("运单查询回调结束：" + ret.ToString());
            Context.Response.Charset = "UTF-8";
            Context.Response.ContentEncoding = System.Text.Encoding.GetEncoding("UTF-8");
            Context.Response.Write(ret.ToString());
            Context.Response.End();
        }

        //支付回调
        [WebMethod(Description = "支付回调")]
        public void XYF_PayBack()
        {
            ILog logJieKou = LogManager.GetLogger("LoggerZhiFu");
            string result = @"{ 
                     'code':'0',  
                     'msg':'请求成功'
                 }";
            JObject ret = JObject.Parse(result);


            Stream postData = Context.Request.InputStream;
            StreamReader sRead = new StreamReader(postData);
            string postContent = sRead.ReadToEnd();
            logJieKou.Info(nameof(XYF_PayBack) + "-" + postContent);
            //order_no=123460&pay_out_trade_no=LAN2021011000000007&pay_status=%E7%94%B3%E8%AF%B7%E6%88%90%E5%8A%9F&cur_oper_user_id=15023692923
            mysqlcli mainsql = new mysqlcli();
            mainsql.openShopServicesql();
            try
            {
                using (TransactionScope tsall = new TransactionScope())
                {
                    var orderid = Context.Request.Form["order_no"];
                    //var payno = Context.Request.Form["pay_out_trade_no"];
                    //var userid = Context.Request.Form["cur_oper_user_id"];
                    //var paytype = Context.Request.Form["pay_status"].ToInt32Null();
                    //付款状态=已付,订单状态=待发货
                    //order_pay_method='2'
                    var sqlcmd = string.Format("update {0} set order_pay_status='2',order_status='1',order_pay_time=NOW(),order_pay_method='2'  where order_number='{1}' ",
                       S_ORDER, orderid);
                    var sqlret = mainsql.SqlExcuteNoReturn(sqlcmd);
                    if (sqlret != 1)
                    {
                        mainsql.closesql();
                        goto EXIT;
                    }

                    mainsql.closesql();
                    tsall.Complete();
                }
            }
            catch (Exception ex)
            {
                logJieKou.Info(ex);
            }

            EXIT:
            logJieKou.Info("支付回调结束：" + ret.ToString());
            Context.Response.Charset = "UTF-8";
            Context.Response.ContentEncoding = System.Text.Encoding.GetEncoding("UTF-8");
            Context.Response.Write(ret.ToString());
            Context.Response.End();
        }


        //放款成功回调
        [WebMethod(Description = "放款成功回调")]
        public void XYF_FangKuanBack()
        {
            ILog logJieKou = LogManager.GetLogger("LoggerZhiFu");
            string result = @"{ 
                     'code':'0',  
                     'msg':'请求成功'
                 }";
            JObject ret = JObject.Parse(result);


            Stream postData = Context.Request.InputStream;
            StreamReader sRead = new StreamReader(postData);
            string postContent = sRead.ReadToEnd();
            logJieKou.Info(nameof(XYF_FangKuanBack) + "-" + postContent);

            try
            {
                var orderid = Context.Request.Form["order_no"];
                var price = Context.Request.Form["amount"];
                var fwf = Context.Request.Form["commi_amount"];
                var userid = Context.Request.Form["user_id"];
                var paytype = Context.Request.Form["loan_status"].ToInt32();
                //var orderid = json.Value<string>("order_no");
                //var price = json.Value<string>("amount");
                //var fwf = json.Value<string>("commi_amount");
                //var userid = json.Value<string>("user_id");
                //var paytype = json.Value<string>("loan_status").ToInt32();

            }
            catch (Exception ex)
            {
                logJieKou.Info(ex);
            }

            EXIT:
            logJieKou.Info("放款回调结束：" + ret.ToString());
            Context.Response.Charset = "UTF-8";
            Context.Response.ContentEncoding = System.Text.Encoding.GetEncoding("UTF-8");
            Context.Response.Write(ret.ToString());
            Context.Response.End();
        }

        //开户回调
        [WebMethod(Description = "开户回调")]
        public void XYF_KaiHuBack()
        {
            ILog logJieKou = LogManager.GetLogger("LoggerZhiFu");
            string result = @"{ 
                     'result':'success',  
                     'msg':'请求成功'
                 }";
            JObject ret = JObject.Parse(result);


            Stream postData = Context.Request.InputStream;
            StreamReader sRead = new StreamReader(postData);
            string postContent = sRead.ReadToEnd();
            logJieKou.Info("小程序回调开始：" + "-" + postContent);

            try
            {
                var json = JsonConvert.DeserializeObject<JObject>(postContent);
                var orderid = json.Value<string>("parent_id");
                var userid = json.Value<string>("user_id");
                var paytype = json.Value<string>("status");//01授权绑定 02解除授权绑定

            }
            catch (Exception ex)
            {
                logJieKou.Info(ex);
            }

            EXIT:
            logJieKou.Info("代付回调结束：" + ret.ToString());
            Context.Response.Charset = "UTF-8";
            Context.Response.ContentEncoding = System.Text.Encoding.GetEncoding("UTF-8");
            Context.Response.Write(ret.ToString());
            Context.Response.End();
        }

        //查询账户状态
        [WebMethod(Description = "查询账户状态")]
        public void XYF_GetUserStatus()
        {
            ILog logJieKou = LogManager.GetLogger("LoggerZhiFu");
            string result = @"{ 
                     'result':'success',  
                     'msg':'请求成功'
                 }";
            JObject ret = JObject.Parse(result);


            Stream postData = Context.Request.InputStream;
            StreamReader sRead = new StreamReader(postData);
            string postContent = sRead.ReadToEnd();
            logJieKou.Info("小程序回调开始：" + "-" + postContent);

            try
            {
                var json = JsonConvert.DeserializeObject<JObject>(postContent);
                var userid = json.Value<string>("user_id");

                var data = new JObject();
                data.Add("user_id", userid);//用户ID
                data.Add("parent_id", "");
                data.Add("status", 0);
                data.Add("createdt", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")); //创建时间
                data.Add("modifydt", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")); //创建时间

                ret.Add("data", data);
            }
            catch (Exception ex)
            {
                logJieKou.Info(ex);
            }

            EXIT:
            logJieKou.Info("代付回调结束：" + ret.ToString());
            Context.Response.Charset = "UTF-8";
            Context.Response.ContentEncoding = System.Text.Encoding.GetEncoding("UTF-8");
            Context.Response.Write(ret.ToString());
            Context.Response.End();
        }

        //查询账户信息
        [WebMethod(Description = "查询账户信息")]
        public void XYF_GetUserInfo()
        {
            ILog logJieKou = LogManager.GetLogger("LoggerZhiFu");
            string result = @"{ 
                     'result':'success',  
                     'msg':'请求成功'
                 }";
            JObject ret = JObject.Parse(result);


            Stream postData = Context.Request.InputStream;
            StreamReader sRead = new StreamReader(postData);
            string postContent = sRead.ReadToEnd();
            logJieKou.Info("小程序回调开始：" + "-" + postContent);

            try
            {
                var json = JsonConvert.DeserializeObject<JObject>(postContent);
                var userid = json.Value<string>("user_id");

                var data = new JObject();
                data.Add("userid", userid);//用户ID
                data.Add("usedname", "吴先生");
                data.Add("mobile_no", "15023692923");
                data.Add("status", 0);

                ret.Add("data", data);
            }
            catch (Exception ex)
            {
                logJieKou.Info(ex);
            }

            EXIT:
            logJieKou.Info("代付回调结束：" + ret.ToString());
            Context.Response.Charset = "UTF-8";
            Context.Response.ContentEncoding = System.Text.Encoding.GetEncoding("UTF-8");
            Context.Response.Write(ret.ToString());
            Context.Response.End();
        }

        #region 信用付查询用户信息

        [WebMethod(Description = "查询是否可用信用付")]
        public string Shop_XinYongIsShow(string msg)
        {
            ILog loginfo = LogManager.GetLogger("LoggerJieKou");
            loginfo.Info(nameof(Shop_XinYongIsShow) + ":" + msg);
            ComThriftMsg ret = new ComThriftMsg();
            ret.Byte_Flag = (sbyte)-1;
            ret.Map_Args = new Dictionary<string, string>();
            ret.Map_Args.Add("ErrorMsg", "服务器异常");
            byte[] bytrcv = Convert.FromBase64String(msg);
            var isjson = true;
            ComThriftMsg comrcv = CommonTools.Json_ByteTOComThriftAESD(bytrcv, ref isjson);

            mysqlcli mainsql = new mysqlcli();

#if DEBUG
            mainsql.opensql(new SqlInfo()
            {
                String_sqlip = "127.0.0.1",
                String_sqlname = "shopping",
                String_sqlport = "3306",
                String_sqlpwd = "123456",
                String_sqluser = "root"
            });
#else
            mainsql.openShopServicesql();
#endif

            try
            {
                using (TransactionScope tsall = new TransactionScope())
                {
                    var orderid = comrcv.Map_Args["orderid"]; //订单号
                    var model = mainsql.SqlExcuteWithReturn($"select t1.order_price,t2.user_phone,t2.user_chxinyong,t3.user_chxinyong as shop_chxinyong,t3.c_code from {BIAOORDER} t1 left join {BIAOUSER} t2 on t1.order_to_user_id=t2.user_onlyid left join {BIAOCH} t3 on t1.shop_id=t3.shop_id where t1.order_id='{orderid}'").ToModels().FirstOrDefault();
                    ret.Map_Args.Add("Result", "0");//0未开通,1已开通
                    if (model != null)
                    {
                        var userisopen = model["user_chxinyong"].ToInt32Null();
                        var shopisopen = model["shop_chxinyong"].ToInt32Null();
                        if (!userisopen.HasValue)
                        {
                            mainsql.closesql();//没有权限
                            ret.Byte_Flag = (sbyte)1;
                            goto EXIT;
                        }
                        var userphone = model["user_phone"];
                        var shopphone = model["c_code"];
                        var price = model["order_price"].ToDouble();
                        Dictionary<string, object> paramMap = new Dictionary<string, object>();
                        paramMap.Add("user_no", userphone);
                        paramMap.Add("operator_user_no", userphone);
                        paramMap.Add("receipt_user_no", shopphone);
                        paramMap.Add("pay_amount", price);
                        var userIp = string.Empty;
                        try
                        {
                            userIp = Context.Request.UserHostAddress;
                        }
                        catch { }
                        string tf_sign = ZhiFuSignature.GetTestSignature("tf56pay.mWallet.queryCreditAccount", "02", userIp, paramMap);
                        paramMap.Add("tf_sign", tf_sign);
                        paramMap.Remove("dog_sk");
                        string jsonStr = JsonConvert.SerializeObject(paramMap);
                        string retsult = JsonPostWebRequestForm(ZhiFuSignature.chuanhuaurl, paramMap);
                        if (string.IsNullOrWhiteSpace(retsult))
                        {
                            ret.Map_Args["ErrorMsg"] = "传化接口请求错误";
                            mainsql.closesql();
                            goto EXIT;
                        }
                        JObject retsultJson = JsonConvert.DeserializeObject(retsult) as JObject;
                        if ("GP_00".Equals(retsultJson.Value<string>("code")) && "GPBIZ_00".Equals(retsultJson.Value<string>("biz_code")))
                        {
                            JObject data = JsonConvert.DeserializeObject<JObject>(retsultJson.Value<string>("data"));
                            var status = data.Value<string>("access_status");
                            if ("1".Equals(status))//不可用,显示异常信息
                            {
                                ret.Map_Args.Add("reamrk", data.Value<string>("reamrk"));
                                ret.Map_Args["Result"] = "2";
                            }
                            else if ("2".Equals(status))//可用
                            {
                                mainsql.SqlExcuteNoReturn($"update {BIAOORDER} as o,{BIAOCH} as c,{BIAOUSER} as s set c.user_chxinyong=2,s.user_chxinyong=2 where o.order_to_user_id=s.user_onlyid and o.shop_id=c.shop_id and o.order_id='{orderid}'");
                                ret.Map_Args.Add("available_balance", data.Value<string>("available_balance"));//可用额度
                                ret.Map_Args.Add("credit_balance", data.Value<string>("credit_balance")); //信用额度
                                ret.Map_Args["Result"] = "1";
                            }
                        }
                    }
                    ret.Map_Args["ErrorMsg"] = "操作成功";
                    mainsql.closesql();
                    tsall.Complete();
                    ret.Byte_Flag = (sbyte)1;
                }
            }
            catch (Exception ex)
            {
                mainsql.closesql();
                ret.Map_Args["ErrorMsg"] = ex.Message;  //参数错误
                loginfo.Info(ex);
            }

            EXIT:
            byte[] retb = CommonTools.Json_ComThriftTOByteAESE(ret, isjson);
            string retstr = Convert.ToBase64String(retb);
            return retstr;
        }


        [WebMethod(Description = "查询信用付是否成功,未成功则取消支付单")]
        public string Shop_XinYongPayBlack(string msg)
        {
            ILog loginfo = LogManager.GetLogger("LoggerJieKou");
            loginfo.Info(nameof(Shop_XinYongPayBlack) + ":" + msg);
            ComThriftMsg ret = new ComThriftMsg();
            ret.Byte_Flag = (sbyte)-1;
            ret.Map_Args = new Dictionary<string, string>();
            ret.Map_Args.Add("ErrorMsg", "服务器异常");
            byte[] bytrcv = Convert.FromBase64String(msg);
            var isjson = true;
            ComThriftMsg comrcv = CommonTools.Json_ByteTOComThriftAESD(bytrcv, ref isjson);

            mysqlcli mainsql = new mysqlcli();

#if DEBUG
            mainsql.opensql(new SqlInfo()
            {
                String_sqlip = "127.0.0.1",
                String_sqlname = "shopping",
                String_sqlport = "3306",
                String_sqlpwd = "123456",
                String_sqluser = "root"
            });
#else
            mainsql.openShopServicesql();
#endif

            try
            {
                using (TransactionScope tsall = new TransactionScope())
                {
                    var orderid = comrcv.Map_Args["OrderId"]; //订单
                    var orderModel = mainsql.SqlExcuteWithReturn($"select * from {BIAOORDER} where order_id='{orderid}'").ToModels().FirstOrDefault();
                    ret.Map_Args.Add("Result", "0");//0未支付,1已支付
                    if (orderModel == null)
                    {
                        ret.Map_Args["ErrorMsg"] = "订单不存在";
                        mainsql.closesql();
                        goto EXIT;
                    }
                    else if (orderModel["order_pay_status"] == "2")
                    {
                        ret.Map_Args["Result"] = "1";
                    }
                    else
                    {
                        Dictionary<string, object> paramMap = new Dictionary<string, object>();
                        paramMap.Add("channel_serial_no", orderModel["order_number"]);
                        var userIp = string.Empty;
                        try
                        {
                            userIp = Context.Request.UserHostAddress;
                        }
                        catch { }
                        string tf_sign = ZhiFuSignature.GetTestSignature("tf56pay.mWallet.queryCreditPayOrder", "01", userIp, paramMap);
                        paramMap.Add("tf_sign", tf_sign);
                        paramMap.Remove("dog_sk");
                        string jsonStr = JsonConvert.SerializeObject(paramMap);
                        string retsult = JsonPostWebRequestForm(ZhiFuSignature.chuanhuaurl, paramMap);
                        if (string.IsNullOrWhiteSpace(retsult))
                        {
                            ret.Map_Args["ErrorMsg"] = "传化接口请求错误";
                            mainsql.closesql();
                            goto EXIT;
                        }
                        JObject retsultJson = JsonConvert.DeserializeObject(retsult) as JObject;
                        if ("GP_00".Equals(retsultJson.Value<string>("code")) && "GPBIZ_00".Equals(retsultJson.Value<string>("biz_code")))
                        {
                            JObject data = JsonConvert.DeserializeObject<JObject>(retsultJson.Value<string>("data"));
                            var status = data.Value<string>("pay_status");
                            if ("0".Equals(status) || "5".Equals(status))
                            {
                                var sqlcmd = string.Format("update {0} set order_pay_status='2',order_status='1',order_pay_time=NOW(),order_pay_method='2'  where order_id='{1}' ",
                         S_ORDER, orderid);
                                mainsql.SqlExcuteNoReturn(sqlcmd);
                                ret.Map_Args["Result"] = "1";
                            }
                        }
                    }
                    ret.Map_Args["ErrorMsg"] = "操作成功";
                    mainsql.closesql();
                    tsall.Complete();
                    ret.Byte_Flag = (sbyte)1;
                }
            }
            catch (Exception ex)
            {
                mainsql.closesql();
                ret.Map_Args["ErrorMsg"] = ex.Message;  //参数错误
                loginfo.Info(ex);
            }

            EXIT:
            byte[] retb = CommonTools.Json_ComThriftTOByteAESE(ret, isjson);
            string retstr = Convert.ToBase64String(retb);
            return retstr;
        }

        /// <summary>
        /// 支付失败的订单撤销
        /// </summary>
        /// <param name="orderid"></param>
        private void cancelPayOrder(string orderid)
        {
            ILog loginfo = LogManager.GetLogger("LoggerJieKou");
            loginfo.Info(nameof(setOrderStatus));
            try
            {
                Dictionary<string, object> paramMap = new Dictionary<string, object>();
                paramMap.Add("channel_serial_no", orderid);
                var userIp = string.Empty;
                try
                {
                    userIp = Context.Request.UserHostAddress;
                }
                catch { }
                string tf_sign = ZhiFuSignature.GetTestSignature("tf56pay.mWallet.cancelCreditPayOrder", "01", userIp, paramMap);
                paramMap.Add("tf_sign", tf_sign);
                paramMap.Remove("dog_sk");
                string jsonStr = JsonConvert.SerializeObject(paramMap);
                string retsult = JsonPostWebRequestForm(ZhiFuSignature.chuanhuaurl, paramMap);
                loginfo.Info(retsult);
                JObject retsultJson = JsonConvert.DeserializeObject(retsult) as JObject;
                if ("GP_00".Equals(retsultJson.Value<string>("code")) && "GPBIZ_00".Equals(retsultJson.Value<string>("biz_code")))
                {
                }
            }
            catch { }
        }
        /// <summary>
        /// 通知订单状态
        /// notify_status
        /// </summary>
        /// <param name="orderid"></param>
        private int setOrderStatus(string orderid, string liushui, Dictionary<string, object> paramMap)
        {
            ILog loginfo = LogManager.GetLogger("LoggerJieKou");
            loginfo.Info(nameof(setOrderStatus));
            try
            {
                paramMap.Add("order_no", orderid);
                paramMap.Add("channel_serial_no", liushui);
                //paramMap.Add("notify_status", orderid);// 1 - 发货，2 - 确认收获，3 - 确认退款
                var userIp = string.Empty;
                try
                {
                    userIp = Context.Request.UserHostAddress;
                }
                catch { }
                string tf_sign = ZhiFuSignature.GetTestSignature("tf56pay.CreditPay.OrderStatusNotify", "01", userIp, paramMap);
                paramMap.Add("tf_sign", tf_sign);
                paramMap.Remove("dog_sk");
                string jsonStr = JsonConvert.SerializeObject(paramMap);
                string retsult = JsonPostWebRequestForm(ZhiFuSignature.chuanhuaurl, paramMap);
                loginfo.Info(retsult);
                JObject retsultJson = JsonConvert.DeserializeObject(retsult) as JObject;
                if ("GP_00".Equals(retsultJson.Value<string>("code")) && "GPBIZ_00".Equals(retsultJson.Value<string>("biz_code")))
                {
                    return retsultJson.Value<int>("pay_status");
                }
            }
            catch { }
            return -1;
        }
        #endregion
    }
}